package com.ican.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.ican.common.BusinessException;
import com.ican.nc.RuleItem;

public class ObjectSeriaryUtil {

    public static String objectSeriary2String(Object o) throws BusinessException{
        try{
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(o);  
            return byteArrayOutputStream.toString("ISO-8859-1");
        }catch(Exception e){
            throw new BusinessException("object seriary 2 string failed", e);
        }
    }
    
    public static Object stringUnseriary2Object(String s) throws BusinessException{
        try{
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(s.getBytes("ISO-8859-1"));
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); 
            return objectInputStream.readObject();
        }catch(Exception e){
            throw new BusinessException("string unseriary 2 object failed", e);
        }
    }
    
    public static void main(String[] args){
        RuleItem i = new RuleItem();
        i.setHttp("asdfa");
        i.setSubStrFrom("21312");
        String s = objectSeriary2String(i);
        System.out.println(s);
        RuleItem o = (RuleItem)stringUnseriary2Object(s);
        System.out.println(o.getHttp());
        System.out.println(o.getSubStrFrom());
    }
}
